<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax XHR</title>
</head>
<body>
    <form id="form" action="/login" >
        <input type="text" name="name" id=""><br />
        <input type="text" name="pwd" id=""><br />
        <button type="submit">提交</button>
    </form>
    <script>
        window.onload = function() {
            var form = document.getElementById('form')
            form.onsubmit = function() {
                let data = {
                    name: form.name.value,
                    pwd: form.pwd.value
                }
                ajax({
                    // url: '/login',
                    url: 'http://localhost:3001/login',
                    method: 'POST',
                    data: data,
                    dataType: 'json',
                    success: function(data) {
                        console.log(
                            data
                        )
                    },
                    error: function(err) {
                        
                    }
                })
                return false
            }
        }



        const encodeParam = function(param) {
            let a = []
            for (let key in param) {
                a.push(`${key}=${param[key]}`)
            }
            return a.join('&')
        }

        let ajax = function(options) {
            var xhr = new XMLHttpRequest();
            
            if (options.method.toUpperCase() === 'POST') {
                xhr.open(
                    options.method,
                    options.url,
                    true
                )
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                // 发送请求
                xhr.send(encodeParam(options.data))
            } else if (options.method.toUpperCase() === 'GET') {
                xhr.open(
                    options.method,
                    options.url + '?'+encodeParam(param),
                    true
                )
                xhr.send()
            }

            // 接受返回值
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status <= 300 || xhr.status === 304) {
                        let res = xhr.response
                        if (options.dataType === 'json') {
                            res = JSON.parse(res);
                        }
                        options.success && options.success(res)
                    } else {
                        options.error && options.error(xhr.response)
                    }
                }
            }

        }

    </script>
</body>
</html>